import { getBasisUrl } from 'src/boot/template/template-upload'
import md5 from 'js-md5'
import state from '../../store/state'
import { saveAs } from 'file-saver'
import axios from 'axios'

/**
 * 通过blob将二进制流保存成文件
 * @param url oss文件地址 fileName 文件名(xxx.xls)
 * @return {Promise<unknown>} promise
 */
export function saveFileForBlob (url, fileName) {
  return new Promise((resolve) => {
    axios.get(url, {
      responseType: 'blob'
    }).then(response => {
      // 创建blob实例
      let blob = new Blob([response.data], { type: 'text/plain;charset=utf-8' })
      saveAs(blob, `${fileName}`)
    })
    resolve()
  })
}

// 上传文件
export function getUploadPath (file, path) {
  // 生成随机文件名， 原文件名 + 时间戳 + 随机字符串
  const fileName = file[0].name + Number(new Date()) + Math.random().toString(36).slice(-8)
  const index = file[0].name.lastIndexOf('.')
  const suffix = file[0].name.substring(index)
  // md5转换
  const fileNameNew = md5(fileName)
  const uploadPath = `${state.userInfo.tenant_id}/${path}${state.userInfo.tenant_id}/${fileNameNew}${suffix}`
  // const { code } = await uploadFlie(uploadPath, file[0], fileName)
  return { fileNameNew, uploadPath }
}

export async function getServerPath () {
  const { code, data } = await getBasisUrl()
  if (code !== '1200') {
    this.$showErrTips('获取服务器地址异常，请稍后重试')
    return null
  } else {
    return data
  }
}

export function showErrTips (tips) {
  this.$q.dialog({
    title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>提示</p>`,
    html: true,
    message: tips,
    ok: {
      unelevated: true,
      label: '确认'
    }
  })
}
